package com.xiguthings.xiniu.iot.post.poster;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiguthings.xiniu.iot.common.PostData;

public class PostDataBuffer {
	private Logger LOGGER = LoggerFactory.getLogger(PostDataBuffer.class);
	// 数据之间的分割符号
	private static final String dividedSymbols = ",";
	private static final String startStr = "[";
	private static final String endStr = "]";

	private String url;
	private long interval;
	private int batchSize;

	private long lastFlushTime;

	private Thread aotuFlushThread;

	private StringBuilder postDataStrBuffer = new StringBuilder();

	private int poastDataCount = 0;

	private SendPostThreadPool sendPostThreadPool;

	public PostDataBuffer(long interval, int batchSize, String url, SendPostThreadPool sendPostThreadPool) {
		super();
		postDataStrBuffer.append(startStr);
		this.url = url;
		this.interval = interval;
		this.batchSize = batchSize;
		this.sendPostThreadPool = sendPostThreadPool;

		aotuFlushThread = new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {

					// 沒有到達自動flush的時間
					if (System.currentTimeMillis() - lastFlushTime < interval) {
						continue;
					}
					flush();
				}
			}
		});
		aotuFlushThread.start();
	}

	/**
	 * 向缓冲区中添加数据
	 * 
	 * @param postData
	 */
	public synchronized void add(PostData postData) {
		poastDataCount++;
		postDataStrBuffer.append(postData.getData());
		postDataStrBuffer.append(dividedSymbols);
		if (poastDataCount >= batchSize) {
			flush();
		}

	}

	/**
	 * 执行发送post
	 */
	public synchronized void flush() {

		// 緩存中沒有數據
		if (poastDataCount == 0) {
			return;
		}

		// 拼装数据，即当成了一个单独的发送请求
		PostData sendPostData = new PostData();
		sendPostData.setUrl(url);
		sendPostData.setBatchSize(1);
		sendPostData.setInterval(interval);
		String data = postDataStrBuffer.substring(0, postDataStrBuffer.length() - 1);
		data += endStr;
		sendPostData.setData(data);
		// postData.setCount(0);
		sendPostThreadPool.executeSendPost(sendPostData);
		lastFlushTime = System.currentTimeMillis();
		LOGGER.info("批量发送 {} 条", poastDataCount);
		poastDataCount = 0;
		postDataStrBuffer = new StringBuilder();
		postDataStrBuffer.append(startStr);
	}
}
